import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xr_base/styles.dart';
import 'package:xr_base/util.dart';

import 'dart:typed_data';
import 'dart:ui';

double screenWidth(BuildContext context) {
  return MediaQuery.of(context).size.width;
}

double screenHeight(BuildContext context) {
  return MediaQuery.of(context).size.height;
}

double statusBarHeight(BuildContext context) {
  return MediaQuery.of(context).padding.top;
}

// Widget get commonSmallPlaceholderIcon {
//   return localImage(ImageConstants.ic_app_global_placeholder_icon, width: 40, height: 40, fit: BoxFit.contain);
// }

class CustomCacheManager {
  static const key = 'mkniaCustomCacheKey';

  static CustomCacheManager? _instance;

  CacheManager? _cacheManager;

  CacheManager? get cacheManager => _cacheManager;

  static CustomCacheManager getInstance() {
    if (_instance == null) {
      _instance = CustomCacheManager._internal();
    }
    return _instance!;
  }

  /// 构造函数私有化，防止被误创建
  CustomCacheManager._internal() {
    _cacheManager = CacheManager(
      Config(
        key,
        stalePeriod: const Duration(days: 3),
        maxNrOfCacheObjects: 100,
        repo: JsonCacheInfoRepository(databaseName: key),
      ),
    );
  }

  /// 清空缓存
  Future<void>? emptyCache() => _cacheManager?.emptyCache();
}

Widget cachedImage(String url,
    {double? width,
    double? height,
    String? cacheKey,
    BoxFit fit = BoxFit.cover,
    Widget? placeholderContain,
    Widget? errorContain}) {
  return CachedNetworkImage(
      height: height,
      width: width,
      fit: fit,
      cacheKey: cacheKey,
      cacheManager: CustomCacheManager.getInstance().cacheManager,
      placeholder: (
        BuildContext context,
        String url,
      ) =>
          placeholderContain ?? Container(color: Colors.grey[200]),
      errorWidget: (
        BuildContext context,
        String url,
        dynamic error,
      ) =>
          errorContain ?? Icon(Icons.error),
      imageUrl: url);
}

/// 本地图片
Widget localImage(String name, {BoxFit? fit, double? width, double? height}) {
  return Image.asset(
    Utils.getImgPath(name),
    fit: fit,
    width: width,
    height: height,
  );
}

/// 错误提示样式的toast
void showWarnToast(String text) {
  Fluttertoast.showToast(
      msg: text,
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.CENTER,
      backgroundColor: Colors.red,
      textColor: Colors.white);
}

/// 普通提示样式的toast
void showToast(String text) {
  Fluttertoast.showToast(
    msg: text,
    toastLength: Toast.LENGTH_LONG,
    gravity: ToastGravity.CENTER,
  );
}

// Widget backWidget(BuildContext context, {Function()? onBackTap, String? icon}) {
//   return InkWell(
//     onTap: () {
//       if (onBackTap != null) {
//         onBackTap();
//       } else {
//         FocusScope.of(context).unfocus();
//         Navigator.pop(context);
//       }
//     },
//     child: Container(
//       width: Dimens.dn_25,
//       height: Dimens.dn_25,
//       alignment: Alignment.centerLeft,
//       padding: EdgeInsets.only(top: Dimens.dn_4, bottom: Dimens.dn_4, right: Dimens.dn_4),
//       child: localImage(icon ?? ImageConstants.ic_arrow_right),
//     ),
//   );
// }

showCommonDialog(
  BuildContext context,
  Function() ok, {
  String? title,
  String? no,
  TextStyle? noTextStyle,
  String? yes,
  TextStyle? yesTextStyle,
  Widget? content,
  Function()? cancel,
}) {
  showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(
            title ?? 'Are you sure you want to unfollow?',
            style: TextStyles.ts_18_w500_000000,
          ),
          content: content,
          actions: [
            CupertinoDialogAction(
              child: Text(
                no ?? 'NO',
                style: noTextStyle,
              ),
              onPressed: () {
                Navigator.pop(context);
                if (cancel != null) {
                  cancel();
                }
              },
            ),
            CupertinoDialogAction(
              child: Text(
                yes ?? 'YES',
                style: yesTextStyle,
              ),
              onPressed: () {
                Navigator.pop(context);
                ok();
              },
            )
          ],
        );
      });
}

/// 获取截取图片的数据
Future<Uint8List?> getImageData(GlobalKey _repaintKey) async {
  ByteData? byteData = await getImageByteData(_repaintKey);
  if (byteData != null) {
    Uint8List? imageBytes = byteData.buffer.asUint8List();
    return imageBytes;
  }
  return null;
}

Future<ByteData?> getImageByteData(GlobalKey _repaintKey) async {
  BuildContext? buildContext = _repaintKey.currentContext;
  if (buildContext != null) {
    RenderRepaintBoundary? boundary = buildContext.findRenderObject() as RenderRepaintBoundary?;
    if (boundary == null) {
      return null;
    }
    // 获取当前设备的像素比
    double dpr = window.devicePixelRatio.toDouble();
    // pixelRatio 代表截屏之后的模糊程度，因为不同设备的像素比不同
    // 定义一个固定数值显然不是最佳方案，所以以当前设备的像素为目标值
    var image = await boundary.toImage(pixelRatio: dpr);
    ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
    return byteData;
  }
  return null;
}

Future<File> saveImageWithUint8List(Uint8List uint8List, Directory dir, String fileName) async {
  File _file = File(dir.path + "/" + fileName);
  _file = await _file.writeAsBytes(uint8List);
  return _file;
}
